  
  <script setup>
  import { ref, reactive, onMounted, computed } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { getTreeListAPI, createRoleUserAPI, getRoleDetailAPI, updateRoleAPI } from '@/api/system';
import { ElMessage } from 'element-plus';
  
  const route = useRoute();
  const router = useRouter()
  const activeStep = ref(1);
  // 表单信息
  const roleForm = ref({
    roleName: '',
    remark: '',
    perms: []
  });
  // 表单校验规则
  const roleRules = {
    roleName: [
      { required: true, message: '请输入角色名称', trigger: 'blur' }
    ],
    remark: [
      { required: true, message: '请输入角色描述', trigger: 'blur' }
    ]
  };
  const treeList = ref([]); // 功能节点信息
  const defaultProps = { label: 'title' }; // 默认节点
  const disabledList = ref([]); // 禁用节点
  const roleFormRef = ref(null)
  // 创建一个数组来存储所有的 tree 组件引用
  const treeRefs = ref(null);

// 创建一个数组来存储所有的 disabledTree 组件引用
const disabledTree = ref([]);
let roleId = ref(route.query.id); // 获取当前id
  console.log('id',roleId.value);
  
  const tree = ref(null); // 假设你在模板中已经使用 ref="tree" 注册了树形组件的引用
onMounted(async () => {
    await getTreeList();
    if (roleId.value) {
      await getRoleDetail();
    }
});
  // 步骤回退
  const navigateBack = () => {
    route.back();
  };
  // 下一步
  const nextStep = () => {
  if (activeStep.value === 3) return;
  if (activeStep.value === 1) {
    // 进入下一页之前，要进行校验是否填写了表单
    console.log(roleForm.value);
    
    roleFormRef.value.validate((flag) => {
      if (flag) {
        activeStep.value += 1; // 正确更新响应式变量
      }
    });
  } else if (activeStep.value === 2) {

    roleForm.value.perms = [];
    treeRefs.value.forEach((tree) => {
      roleForm.value.perms.push(tree.getCheckedKeys());
    });
    console.log('第二步获取到的数据',roleForm.value);
    
    // 如果长度为零 没有选中任何东西
    if (roleForm.value.perms.flat().length <= 0) {
      ElMessage.warning('请至少勾选一个权限点');
      return;
    }
    // 回填已经选择的数据
    disabledTree.value.forEach((item, index) => {
      item.setCheckedKeys(roleForm.value.perms[index]);
    });
    // 进入到下一页
    activeStep.value += 1;
  }
};
  // 前一步
  const prevStep = () => {
    if (activeStep.value === 2 || activeStep.value === 3) {
        return activeStep.value--
      }
  };
  // 获取填入的数据列表信息
  const getTreeList = async () => {
    const res = await getTreeListAPI();
    treeList.value = res.data;
    disabledList.value = JSON.parse(JSON.stringify(res.data));
    addDisabled(disabledList.value);
  };
  // 将每个数据都禁用
  const addDisabled = (disabledList) => {
    disabledList.forEach(item => {
        item.disabled = true
        // 递归处理
        if (item.children && item.children.length > 0) {
          addDisabled(item.children)
        }
      })
  };
  // 确认添加/ 编辑
  const confirmAdd = async () => {
     // 编辑角色信息
     console.log(roleForm.value);
     
     if (roleId.value) {
        // 删除多余数据
        delete roleForm.value.userTotal
        await updateRoleAPI(roleForm.value)
      } else {
        await createRoleUserAPI(roleForm.value)
      }
      ElMessage({
        type: 'success',
        message: `${roleId.value ? '编辑' : '添加'}角色成功`
      })
      router.back()
  };
  // 编辑时获取每个节点的选择信息
  const getRoleDetail = async () => {
    const res = await getRoleDetailAPI(roleId.value);
    roleForm.value = res.data
    treeRefs.value.forEach((tree,index) => {
      tree.setCheckedKeys(roleForm.value.perms[index])
    });
    

  };
  </script>



<template>
    <div class="add-role">
      <!-- 头部显示 -->
      <header class="add-header">
        <div class="left">
          <span class="arrow" @click="navigateBack"><i class="el-icon-arrow-left" />返回</span>
          <span>|</span>
          <span>{{ roleId ? '编辑角色' : '添加角色' }}</span>
        </div>
        <div class="right">
          管理员
        </div>
      </header>
      <main class="add-main">
        <div class="step-container">
          <el-steps direction="vertical" :active="activeStep">
            <el-step title="角色信息" />
            <el-step title="权限信息" />
            <el-step title="检查并完成" />
          </el-steps>
        </div>
        <!-- 步骤1 -->
        <div v-show="activeStep == 1" class="form-container">
          <div class="title">角色信息</div>
          <div class="form">
            <el-form ref="roleFormRef"  class="form-box" :model="roleForm" :rules="roleRules">
              <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="roleForm.roleName" />
              </el-form-item>
              <el-form-item label="角色描述" prop="remark">
                <el-input v-model="roleForm.remark" />
              </el-form-item>
            </el-form>
          </div>
        </div>
       <div v-show="activeStep == 2" class="form-container">
          <div class="title">权限配置</div>
          <div class="tree-wrapper">
            <div v-for="item in treeList" :key="item.id" class="tree-item">
              <div class="tree-title">{{ item.title }}</div>
              <el-tree
                ref="treeRefs"
                :data="item.children"
                :props="defaultProps"
                show-checkbox
                check-strictly
                default-expand-all
                :highlight-current="false"
                node-key="id"
              />
            </div>
          </div>
        </div>
        <div v-show="activeStep === 3" class="form-container">
          <div class="title">检查并完成</div>
          <div class="form">
            <div class="info">
              <div class="form-item">角色名称：{{ roleForm.roleName }}</div>
              <div class="form-item">角色描述：{{ roleForm.remark }}</div>
              <div class="form-item">角色权限：</div>
              <div class="tree-wrapper">
                <div v-for="item in disabledList" :key="item.id" class="tree-item">
                  <div class="tree-title">{{ item.title }}</div>
                  <el-tree
                    ref="disabledTree"
                    :data="item.children"
                    show-checkbox
                    check-strictly
                    default-expand-all
                    node-key="id"
                    :props="{ label: 'title'}"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </main>
      <footer class="add-footer">
        <div class="btn-container">
          <el-button v-if="activeStep > 1" @click="prevStep">上一步</el-button>
          <el-button v-if="activeStep < 3" type="primary" @click="nextStep">下一步</el-button>
          <el-button v-if="activeStep === 3" type="primary" @click="confirmAdd">{{ roleId ?'确定编辑' : '确定添加' }}</el-button>
        </div>
      </footer>
    </div>
  </template>

  
  <style scoped lang="scss">
 .add-role {
  background-color: #f4f6f8;
  height: 100vh;
  overflow:hidden;

  .add-header {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    position: absolute;
    top: 64px;
    bottom: 88px;
    width: 100%;
    overflow-y: auto;
    background: #f4f6f8;
    padding: 20px 230px;
    display: flex;
    .step-container {
      height: 400px;
      width: 200px;
    }
    .form-container {
      flex:1;
      background-color: #fff;
      overflow-y: auto;
      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }
      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;
        .el-form {
          display: flex;
          flex-wrap: wrap;
        }
        .info{
          font-size:14px;
          color:#666;
          .form-item{
            margin-bottom:20px;
          }
        }
      }
      .form-box{
        width: 600px;
        display: flex;
        flex-direction: column;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
    z-index: 10001;
  }
  .tree-wrapper {
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
      .tree-item {
        flex: 1;
        padding: 0px 4px;
        text-align: center;
        .tree-title {
          background: #f5f7fa;
          text-align: center;
          padding: 10px 0;
          margin-bottom: 12px;
        }
      }
    }
}
  </style>